package com.book.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CaptchaUtil {
    
    private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    
    /**
     * 生成验证码图片
     */
    public static CaptchaResult generateCaptcha() {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        
        // 设置背景色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);
        
        // 生成随机验证码
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        
        for (int i = 0; i < CODE_LENGTH; i++) {
            char c = CHARS.charAt(random.nextInt(CHARS.length()));
            code.append(c);
            
            // 设置字体
            g2d.setFont(new Font("Arial", Font.BOLD, 20));
            g2d.setColor(getRandomColor());
            
            // 绘制字符
            int x = 20 + i * 20;
            int y = 25 + random.nextInt(10);
            g2d.drawString(String.valueOf(c), x, y);
        }
        
        // 添加干扰线
        for (int i = 0; i < 5; i++) {
            g2d.setColor(getRandomColor());
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g2d.drawLine(x1, y1, x2, y2);
        }
        
        // 添加干扰点
        for (int i = 0; i < 30; i++) {
            g2d.setColor(getRandomColor());
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            g2d.drawOval(x, y, 1, 1);
        }
        
        g2d.dispose();
        
        return new CaptchaResult(image, code.toString());
    }
    
    /**
     * 获取随机颜色
     */
    private static Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }
    
    /**
     * 验证码结果类
     */
    public static class CaptchaResult {
        private BufferedImage image;
        private String code;
        
        public CaptchaResult(BufferedImage image, String code) {
            this.image = image;
            this.code = code;
        }
        
        public BufferedImage getImage() {
            return image;
        }
        
        public String getCode() {
            return code;
        }
    }
} 